package com.zyr.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zyr.model.SecurityUser;
import com.zyr.model.User;
import com.zyr.exception.CustomizeException;
import com.zyr.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author 张雨润
 * @date 2024/7/25 下午8:14
 * @Description 加载用户信息
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (ObjectUtil.isNull(user)) {
            throw new CustomizeException("该用户不存在");
        } else {
            List<String> list = new ArrayList<>();
            String permissions = user.getPermissions();
            if (permissions.contains(",")) {
                list.addAll(Arrays.asList(permissions.split(",")));
            } else {
                list.add(permissions);
            }
            return new SecurityUser(user, list);
        }
    }
}
